﻿using ChoMy.Areas.Admin.Models;
using ChoMy.Constants;
using ChoMy.Helpers;
using ChoMy.Models;
using ChoMy.Models.Data;
using PagedList;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;

namespace ChoMy.Areas.Admin.Controllers
{
    public class ImageController : Controller
    {
        private ChoMyContext db = new ChoMyContext();
        private ImageHelper imgHp = new ImageHelper();
        private FileHelper fileHp = new FileHelper();
        private string title = "ảnh sản phẩm";

        public ImageController()
        {
            ViewBag.Title = title;
        }

        [Authorize(Roles = "Admin, Image Read Public, Image Read Private")]
        public ActionResult Index(int? productId, bool? isTrash, string sortOrder, int? page, int? pageSize)
        {
            if (productId == null)
            {
                return RedirectToAction("BadRequest", "Error");
            }

            Product product = db.Products.Find(productId);

            if (product == null)
            {
                return RedirectToAction("NotFound", "Error");
            }

            ViewBag.Product = product;

            var sortList = new List<string> { "Property.Name", "Width", "Height", "DateModified", "DateCreated" };
            var pageSizeList = new List<int> { 10, 25, 50, 100 };
            int pageNumber = page ?? 1;

            pageSize = pageSize ?? 10;
            sortOrder = sortOrder ?? "DateCreated_desc";
            isTrash = isTrash ?? false;

            ViewBag.IsTrash = isTrash;
            ViewBag.PageSize = pageSize;
            ViewBag.PageSizeDDL = new SelectList(pageSizeList, pageSize);
            ViewBag.ReturnListUrl = Request.Url.AbsoluteUri;

            IQueryable<Image> query = db.Images.Where(x => x.ProductId == product.Id);

            if (User.IsInRole("Image Read Private"))
            {
                query = query.Where(x => x.CreatedBy == User.Identity.Name);
            }

            ViewBag.TrashCount = query.Count(x => x.IsDelete);
            ViewBag.ListCount = query.Count(x => !x.IsDelete);

            query = Sort(query, sortOrder, sortList);

            query = query.Where(x => x.IsDelete == isTrash);

            return View(query.ToPagedList(pageNumber, (int)pageSize));
        }

        [Authorize(Roles = "Admin, Image Read Public,  Image Read Private")]
        public ActionResult _Details(int id)
        {
            Image image = db.Images.Find(id);

            if (User.IsInRole("Image Read Private") && image.CreatedBy != User.Identity.Name)
            {
                return null;
            }

            return PartialView(image);
        }

        [Authorize(Roles = "Admin, Image Create")]
        public ActionResult Create(int? productId, string returnListUrl)
        {
            if (productId == null)
            {
                return RedirectToAction("BadRequest", "Error");
            }

            Product product = db.Products.Find(productId);

            if (product == null)
            {
                return RedirectToAction("NotFound", "Error");
            }

            ViewBag.Product = product;

            ColorDDL(product, null);

            ViewBag.ReturnListUrl = returnListUrl;

            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Image Create")]
        [ValidateAntiForgeryToken]
        public ActionResult Create(ImageCreator model, string returnListUrl)
        {
            Product product = db.Products.Find(model.ProductId);

            if (!String.IsNullOrWhiteSpace(fileHp.Valid(model.Images.FirstOrDefault())))
            {
                ModelState.AddModelError("Images", "Bạn chưa chọn ảnh để tải lên.");
            }

            if (ModelState.IsValid)
            {
                foreach (var img in model.Images)
                {
                    var image = new Image();
                    image.Url = fileHp.Upload(img, product.NameId, "/upload/image/product");
                    image.Height = imgHp.Height(image.Url);
                    image.Width = imgHp.Width(image.Url);
                    image.PropertyId = model.PropertyId;
                    image.ProductId = model.ProductId;

                    db.Images.Add(image);
                    db.SaveChanges();
                }

                string productName = String.Format("{0} - {1}", product.Name, product.Code);

                SaveHistory("Create", productName, model.Images.Count);
                AlertHandling("Create", productName, model.Images.Count);

                if (!String.IsNullOrWhiteSpace(returnListUrl))
                {
                    return Redirect(returnListUrl);
                }

                return RedirectToAction("Index", new { productId = model.ProductId });
            }

            ViewBag.Product = product;

            ColorDDL(product, null);

            ViewBag.ReturnListUrl = returnListUrl;

            return View(model);
        }

        [Authorize(Roles = "Admin, Image Edit Public, Image Edit Private")]
        public ActionResult Edit(int? id, string returnListUrl)
        {
            if (id == null)
            {
                return RedirectToAction("BadRequest", "Error");
            }

            Image image = db.Images.Find(id);

            if (image == null)
            {
                return RedirectToAction("NotFound", "Error");
            }

            if (User.IsInRole("Image Edit Private") && image.CreatedBy != User.Identity.Name)
            {
                return RedirectToAction("Unauthorized", "Error");
            }

            Product product = image.Product;

            ViewBag.Product = product;

            ColorDDL(product, image.PropertyId);

            var model = new ImageEditor();
            model.PropertyId = image.PropertyId;
            model.IsMainImage = (image.Priority != 0
                && image.Priority == db.Images
                .Where(x => x.ProductId == image.ProductId && x.PropertyId == image.PropertyId)
                .Max(x => x.Priority));

            ViewBag.ReturnListUrl = returnListUrl;

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Image Edit Public, Image Edit Private")]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(ImageEditor model, string returnListUrl)
        {
            Image image = db.Images.Find(model.Id);

            if (ModelState.IsValid)
            {               
                if (String.IsNullOrWhiteSpace(fileHp.Valid(model.Image)))
                {
                    fileHp.Delete(image.Url);
                    image.Url = fileHp.Upload(model.Image, image.Product.NameId, "/upload/image/product");
                    image.Height = imgHp.Height(image.Url);
                    image.Width = imgHp.Width(image.Url);
                }

                if (model.IsMainImage == true)
                {
                    image.Priority = db.Images
                        .Where(x => x.ProductId == image.ProductId && x.PropertyId == image.PropertyId)
                        .Max(x => x.Priority) + 1;
                }

                image.PropertyId = model.PropertyId;
                image.DateModified = DateTime.Now;
                image.ModifiedBy = User.Identity.Name;

                db.Entry(image).State = EntityState.Modified;
                db.SaveChanges();

                string productName = String.Format("{0} - {1}", image.Product.Name, image.Product.Code);

                SaveHistory("Edit", productName, image.Id);
                AlertHandling("Edit", productName, image.Id);


                if (!String.IsNullOrWhiteSpace(returnListUrl))
                {
                    return Redirect(returnListUrl);
                }

                return RedirectToAction("Index", new { productId = image.ProductId });
            }

            Product product = image.Product;

            ViewBag.Product = product;

            ColorDDL(product, image.PropertyId);

            ViewBag.ReturnListUrl = returnListUrl;

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Image Delete Public, Image Delete Private")]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id, string returnListUrl)
        {
            Image image = db.Images.Find(id);

            if (User.IsInRole("Image Delete Private") && image.CreatedBy != User.Identity.Name)
            {
                return RedirectToAction("Unauthorized", "Error");
            }

            int productId = image.ProductId;
            string productName = String.Format("{0} - {1}", image.Product.Name, image.Product.Code);

            fileHp.Delete(image.Url);

            db.Images.Remove(image);
            db.SaveChanges();

            SaveHistory("Delete", productName, productId);
            AlertHandling("Delete", productName, productId);

            if (!String.IsNullOrWhiteSpace(returnListUrl))
            {
                return Redirect(returnListUrl);
            }

            return RedirectToAction("Index", new { productId = productId, isTrash = true });
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Image Recycle Public, Image Recycle Private")]
        public ActionResult Recycle(int id)
        {
            Image Image = db.Images.Find(id);

            if (User.IsInRole("Image Recycle Private") && Image.CreatedBy != User.Identity.Name)
            {
                return Json(-1, JsonRequestBehavior.AllowGet);
            }

            Image.IsDelete = Image.IsDelete ? false : true;
            Image.DateModified = DateTime.Now;
            Image.ModifiedBy = User.Identity.Name;

            db.Entry(Image).State = EntityState.Modified;
            db.SaveChanges();

            string productName = String.Format("{0} - {1}", Image.Product.Name, Image.Product.Code);

            if (Image.IsDelete)
            {
                SaveHistory("Recycle-Delete", productName, Image.Id);
            }
            else
            {
                SaveHistory("Recycle-Restore", productName, Image.Id);
            }

            return Json(Image.IsDelete ? 1 : 0, JsonRequestBehavior.AllowGet);
        }

        #region Helpers
        private void SaveHistory(string crud, string productName, int id)
        {
            string type = "Image";

            DateTime dateTime = DateTime.Now;
            string userName = User.Identity.Name;
            string description = "";

            switch (crud)
            {
                case "Create":
                    description = String.Format("<b>{0}</b> tạo mới {1} <b>{2}</b> (Số lượng: <b>{3}</b>)", userName, title, productName, id);
                    break;
                case "Edit":
                    description = String.Format("<b>{0}</b> chỉnh sửa {1} <b>{2}</b> (ID: <b>{3}</b>)", userName, title, productName, id);
                    break;
                case "Delete":
                    description = String.Format("<b>{0}</b> xóa vĩnh viễn {1} <b>{2}</b> (ID: <b>{3}</b>)", userName, title, productName, id);
                    break;
                case "Recycle-Delete":
                    description = String.Format("<b>{0}</b> xóa tạm thời {1} <b>{2}</b> (ID: <b>{3}</b>)", userName, title, productName, id);
                    break;
                case "Recycle-Restore":
                    description = String.Format("<b>{0}</b> khôi phục {1} <b>{2}</b> (ID: <b>{3}</b>)", userName, title, productName, id);
                    break;
            }

            var history = new History();
            history.DateTime = dateTime;
            history.Description = description;
            history.HistoryTypeId = db.HistoryTypes.First(x => x.Name == type).Id;

            db.Histories.Add(history);
            db.SaveChanges();
        }

        private void AlertHandling(string crud, string productName, int id)
        {
            string userName = User.Identity.Name;
            string alertMessage = "";

            switch (crud)
            {
                case "Create":
                    alertMessage = String.Format("Bạn vừa tạo mới {0} <b>{1}</b> (Số lượng: <b>{2}</b>)", title, productName, id);
                    break;
                case "Edit":
                    alertMessage = String.Format("Bạn vừa chỉnh sửa {0} <b>{1}</b> (ID: <b>{2}</b>)", title, productName, id);
                    break;
                case "Delete":
                    alertMessage = String.Format("Bạn vừa xóa vĩnh viễn {0} <b>{1}</b> (ID: <b>{2}</b>)", title, productName, id);
                    break;
            }

            if (!String.IsNullOrWhiteSpace(alertMessage))
            {
                Session["alert-message-" + userName] = alertMessage;
                Session["alert-type-" + userName] = "alert-success";
            }
        }

        private void ColorDDL(Product product, int? propertyId)
        {
            if (db.CategoryPropertyTypes.Any(x => x.CategoryId == product.CategoryId && x.PropertyType.NameId == "color"))
            {
                ViewBag.ColorDDL = new SelectList(
                    db.Properties.Where(x => x.PropertyTypeId == 1).OrderBy(x => x.Name), "Id", "Name", propertyId);
            }
        }

        private IQueryable<Image> Sort(IQueryable<Image> query, string sortOrder, List<string> sortList)
        {
            ViewBag.SortOrder = sortOrder;

            foreach (string sort in sortList)
            {
                ViewData[sort + "Sort"] = sortOrder == sort + "_desc" ? sort : sort + "_desc";
            }

            if (sortOrder.Contains("_desc"))
            {
                sortOrder = sortOrder.Replace("_desc", "");
                query = query.OrderBy(sortOrder + " descending");
                ViewData[sortOrder + "Icon"] = DataTableConstant.DescSortIcon;
            }
            else
            {
                query = query.OrderBy(sortOrder);
                ViewData[sortOrder + "Icon"] = DataTableConstant.AscSortIcon;
            }

            return query;
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }

            base.Dispose(disposing);
        }
        #endregion
    }
}